package top.jle.jpa.basic.dao;

import jakarta.annotation.PostConstruct;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.jle.jpa.basic.util.SnowFlakeIdWorker;

import java.io.Serializable;

@Component
public class GUIDGenerator implements IdentifierGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(GUIDGenerator.class);
    @Value("${sfi-data-center-id:1}")
    private Long dataCenterId;

    private static SnowFlakeIdWorker snowFlakeIdWorker;

    @PostConstruct
    public void init() {
        if(snowFlakeIdWorker==null){
            snowFlakeIdWorker = new SnowFlakeIdWorker(dataCenterId);
            LOGGER.info("SnowFlakeIdWorker  with dataCenterId:{}",dataCenterId);
        }
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor s, Object obj) {
        return snowFlakeIdWorker.nextId();
    }

}
